<template>
	<div class="attendenceRecordContainer">
		<el-dialog	
			  :visible.sync="isShow"	
			  :close-on-click-modal="modalclose"
			  custom-class="el-dialog-bg"
			  :before-close="handleClose">
			  <div slot="title" class="panel_title"><span>新增考勤记录</span></div>
			  
			  <div class="recordlist">
			  	<div class="dialog">
				  	<div class="item">
				  		<el-row>
				  			<el-col :span="12">
				  				<span class="spanlabel">考勤班级</span>
						  		<el-select  v-model="classtext" ref="classtext" filterable @change="selectClass"  placeholder="请选择">
								    <el-option				      
								      v-for="item in clslist"
								      :key="item.classid"
								      :label="item.className"
								      :value="item.classid">
								    </el-option>
							    </el-select>
				  			</el-col>
				  			<el-col v-if="!attend_daydayClass" :span="12">
				  				<span class="spanlabel">考勤课次</span>
						  		<el-select v-model="classSyllabusId" ref="classSyllabusId" @change="selectCourseTime"  placeholder="请选择">
								    <el-option				      
								      v-for="item in times"
								      :key="item.classSyllabusId"
								      :label="item.coursetime"
								      :value="item.classSyllabusId">
								      <!-- <span v-if="item.attendMode==1" style="color: #999999;">{{item.coursetime}}</span>-->
      								   <span v-if="item.attendMode==2" style="color: #333333;">{{item.coursetime}}</span>
								    </el-option>
							    </el-select>
				  			</el-col>

							  <!-- 全日制 -->

							<el-col v-else :span="12">
				  				<span class="spanlabel">考勤日期</span>
								<el-date-picker
									:disabled="attend_pickerDisable"
									v-model="attend_pickerOptionsTime"
									@change="selectCourseTime"
									type="date"
									placeholder="选择日期"
									:picker-options="attend_pickerOptions"
									>
								</el-date-picker>
				  			</el-col>
				  		</el-row>			  		
				  	</div>
				  	<div v-if="!attend_daydayClass" class="item">
				  		<span class="spanlabel">消耗课时/课次：</span>
				  		<el-input v-model="classhour" disabled  style="width:2rem;" placeholder="请输入内容"></el-input>
				  	</div>
					<div v-else class="item">
				  		<span class="spanlabel">消耗课时：</span>
				  		<el-input value="1天" disabled  style="width:2rem;" placeholder=""></el-input>
				  	</div>
				  	<div class="line" v-if="showstudent"></div>
				  	<div class="title">
				  	     <span class="spanlabel" v-if="showstudent">学员列表</span>	
				  	</div>
				  	<el-collapse-transition>
					<div class="studentlist" v-if="showstudent">
				  		<div class="tablecss">
		              		<table style="width:100%;" cellpadding="0" cellspacing="0">
					      			<thead >
					      				<tr>
					      					<th>考勤</th>
					      					<th>姓名</th>
					      					<th>{{attend_daydayClass?'班级名称':'报名课程'}}</th>
					      					<th>家长名称</th>
					      					<th>联系电话</th>
					      					
					      											      											      					
					      				</tr>
					      			</thead>
					      			<tbody  v-if="studentlist.length>0">
					      				<tr v-for="li in studentlist">
					      					<td align="center" style="width:1rem;">
						      					
						      					<el-select v-if="!attend_daydayClass" v-model="li.signinMode"  :disabled="editorAttendence" placeholder="请选择">
												    <el-option
												      v-for="item in attendWay"
												      :key="item.value"
												      :label="item.name"
												      :value="item.value">
												    </el-option>
										    	</el-select>
										    	<el-select v-else v-model="li.signinMode"  :disabled="editorAttendence" placeholder="请选择">
												    <el-option
												      v-for="item in tempattendWay"
												      :key="item.value"
												      :label="item.name"
												      :value="item.value">
												    </el-option>
										    	</el-select>
					      					</td>
					      					<td align="center">{{li.realName}}</td>
					      					<td align="center" v-if="!attend_daydayClass">{{li.courseName}}</td>
											<td align="center" v-else>{{selectClassName}}</td>
					      					<td align="center">{{li.parentName||""}}</td> 					
					      					<td align="center">{{li.phone}}</td>					      										      													   									      										      					
					      				</tr>		      				
					      			</tbody>
					      			<tbody  v-else >
					      				<tr>
					      					<td colspan="11" align="center">暂无数据</td>
					      				</tr>
					      			</tbody>
			      		    </table>
	      		  	</div>			  			
				  	</div>
				  	</el-collapse-transition>
			    </div>
			  </div>
              <div slot="footer" class="footer-btn">
		      	 <el-button @click="btnCancel" class="btnCancel">取 消</el-button>
    			 <el-button  v-if="editorAttendence" style="border-radius: .1rem;width:1.6rem;cursor: not-allowed;color: rgb(153, 153, 153);background-color: rgb(222, 222, 222);" >签到</el-button>
    			 <el-button @click="signbtnOk" v-else class="btnOk" >确定考勤</el-button>
		      </div>     
	    </el-dialog>
		
		
	</div>
	
	
</template>

<script>
	import {mapState,mapGetters,mapActions} from 'vuex'; //先要引入
	let vm;
	export default{
		data(){
			return{
				modalclose:false,
				classtext:'',//班级id
				selectClassName:'',
			    classSyllabusId:'',//课次id
			    classhour:'2',//课时
			    editorAttendence:false,//是否可以编辑学员考勤
				studentlist:[],//班级学员
				times:[],//课次列表
				coursename:'',	//课程名称			
				showstudent:false,//是否显示学员列表				
				attendWay:[],//签到方式
				tempattendWay:[],//签到方式去掉补课
				selectStudentList:[],//签到学员列表
				//全日制
				attend_daydayClass:false,
				attend_pickerDisable:true,
				attend_allowDate:[],
				attend_pickerOptions:{
					disabledDate(time) {
						//排除周末
						// let week=time.getDay()||7;
						// if(week>=6)return true;
						//限定范围 课程开始时间-当前时间
						if(!vm.attend_allowDate.includes(time.getTime()))return true;
						// if(vm.times.length>0){
						// 	// let startstr=vm.times[0].startTime.split(' ')[0];
						// 	// startstr=startstr.replace('-','/');
						// 	// let endstr=vm.times[vm.times.length-1].endTime.split(' ')[0];
						// 	// endstr=endstr.replace('-','/');
						// 	// let starttime=new Date(startstr);
						// 	// let endtime=new Date(endstr);
						// 	// let now=new Date();now.setHours(0,0,0,0);
						// 	// if(endtime>now)endtime=now;
						// 	// if(time<vm.attend_minTime||time>vm.attend_maxTime)return true;
						// }
						return false;
					},
				},
				attend_pickerOptionsTime:'',
				attend_daydayClassSyllabusId:[]
			}
		},
		methods:{
			/**数据初始化**/
			initData(){
				//获取数据字典
                let dicdata = tool.getItem(lsKey.dict,true);
                this.attendWay = dicdata["signin_mode"];
                
                for(let i=0;i<this.attendWay.length;i++){
                	let d = this.attendWay[i];
                	if(d["value"]!=4){
                		this.tempattendWay.push({name:d["name"],value:d["value"]})
                	}
                }              
                this.selectStudentList=[];
                this.studentlist=[];
                this.times=[];
                this.classtext='';
                this.classhour='';
                this.showstudent=false;
                this.coursename='';
                this.classSyllabusId=''; 
				this.editorAttendence=true;
				//全日制
				this.attend_pickerDisable=true;
				this.attend_pickerOptionsTime='';
			},
			/**关闭对话框**/
			handleClose(){						
				this.initData();
				this.$store.dispatch('createAttendenceRecord/hidecreateAttendenceRecordPanel');	
			},
			/**取消**/
			btnCancel(){
				this.initData();
				this.$store.dispatch('createAttendenceRecord/hidecreateAttendenceRecordPanel');	
			},
			/**选项发生变化**/
			selectStudent(selection){
				//alert(123)
				// this.selectStudentList=selection;
			},
			signbtnOk(){
				
				let user = tool.getItem(lsKey.user,true);			   
				let paras=[];
				this.selectStudentList=this.studentlist;
				let rules=[];
				let $classtext = this.$refs.classtext;
				let $classSyllabusId = this.$refs.classSyllabusId;
				
				
				rules.push({
						judge : $classtext.value,
						focus : $classtext,
						tips : '请选择班级'
				});
				if(!this.attend_daydayClass)
					rules.push({
							judge : $classSyllabusId.value,
							focus : $classSyllabusId,
							tips : '请选择课次'
					});
				else{
					rules.push({
						judge : this.attend_pickerOptionsTime,
						focus : $classSyllabusId,
						tips : '请选择考勤日期'
					});
				}
				
				if(!tool.validate(rules)) {
	            	
					return;
				}
				for(let i=0;i<this.selectStudentList.length;i++){
					    let usehour=this.classhour;
					    //请假不消耗课时
					    if(this.selectStudentList[i].signinMode==3){
					    	usehour=0;
						}
						if(!this.attend_daydayClass)
							paras.push({
								classSyllabusId: this.classSyllabusId,
								classId:this.classtext,
								studentId: this.selectStudentList[i].studentId,
								signinMode: this.selectStudentList[i].signinMode,
								consumeHour: usehour,
								siginUserId: user.userId,
								signinTime: tool.DateToString(new Date(),"yyyy-MM-dd HH:mm:ss")
							});
						else{
							for(let k=0;k<this.attend_daydayClassSyllabusId.length;k++){
								paras.push({
									classSyllabusId: this.attend_daydayClassSyllabusId[k],
									classId:this.classtext,
									studentId: this.selectStudentList[i].studentId,
									signinMode: this.selectStudentList[i].signinMode,
									// consumeHour: this.selectStudentList[i].signinMode==3?0:(k==0?1:0),
									siginUserId: user.userId,
									courseType:2,
									signinTime: tool.DateToString(new Date(),"yyyy-MM-dd HH:mm:ss")
								});
							}
						}
					
				}
				// console.log(this.selectStudentList)
				
				
				
				if(paras.length<=0){
					this.$message({
			          message: '至少签到一个学员',
			          type: 'warning'
			        });
					return;
				}
		
				
				//新增考勤记录
				 console.log(paras)
				api.addAttendence(paras).then(function(data){
					// console.log(data)
					let Data = data.data;
					if(Data.successCount>0){
						  vm.$message({
					          message: '成功签到'+Data.successCount+"位学员",
					          type: 'success'
			        		});
						  vm.$store.dispatch('createAttendenceRecord/hidecreateAttendenceRecordPanel');
						  vm.$parent.initData();
						  vm.initData();
					}else{
						vm.$message({
					          message: '有'+Data.conflictRow.length+"位学员已签到过",
					          type: 'warning'
			        		});
					}
				})
				
			},
			/**
			 * 选择班级
			 */
			selectClass(val){			
				let self=this;	
				this.showstudent=false;			
				this.clslist.forEach(d=>{
					if(d.classid==val)self.selectClassName=d.className;
				});
				let paras={classId:val,courseStatus:2};

				this.updateDayDayClassVisible(val);
				//获取学生列表
				// api.getClassAttendStudentList(paras).then(function(data){
					 
				// 	 vm.classSyllabusId="";
				// 	 vm.studentlist = [];
				// 	if(data.result=="操作成功"){
						 
				// 		 vm.studentlist=data.studentList.map(function(row){
				// 		 	let parentName="";
				// 		 	let phone = "";
				// 		 	if(row.studentParentEntityList==null){
				// 		 		parentName="";
				// 		 		phone="";
				// 		 	}else{
				// 				if(row.studentParentEntityList.length>0)
				// 				{
				// 					parentName=row.studentParentEntityList[0].parentName;
				// 		 			phone=row.studentParentEntityList[0].phone;
				// 				}
				// 		 	}
			    //         	return {
			    //         		   signinMode:1,
			    //         		   realName:row.realName,
			    //         		   courseName:row.courseName,
			    //         		   parentName:parentName,
			    //         		   phone:phone,
			    //         		   studentId:row.studentId
			    //         	}
			    //       });
				// 	}
				// 	// return api.getSyllabusByClass(paras);
				// });
				//获取课次列表
				vm.classSyllabusId="";
				api.getSyllabusByClass(paras).then(function(data){
					
					vm.times=[];
					if(data.result=="操作成功"){
						
                      //筛选还没签到的课次
                    //   for(let k=0;k<data.list.length;k++){
					// 	if(data.list[k].attendMode==2)
					// 	{
					// 		vm.times.push(data.list[k]);
					// 	}
					//   }
					  vm.times=data.list;
                    //  vm.classSyllabusId=vm.times[0].classSyllabusId;
                      for(let i =0;i<vm.times.length;i++){
                      	
                      	vm.times[i].coursetime="第"+vm.times[i].orderBy+"次";
                      	
					  }
					  //全日制
					  vm.attend_pickerDisable=true;
					  vm.attend_allowDate=[];
                      if(vm.times.length>0){
						vm.attend_pickerDisable=false;
						vm.attend_pickerOptionsTime='';
						vm.times.forEach(d=>{
							let startstr=d.startTime.split(' ')[0];
							startstr=startstr.replace(/-/g,'/');
							let day=(new Date(startstr)).getTime();
							if(!vm.attend_allowDate.includes(day))
								vm.attend_allowDate.push(day);
						});
						
					  }
					}
				})
				
			},
			/**
			 * 选择课次
			 */
			selectCourseTime(val){
				
				let psyllabusId=val;
				if(!this.attend_daydayClass){
					for(let i =0;i<vm.times.length;i++){
						
						if(vm.times[i].classSyllabusId==val){
							vm.classhour=vm.times[i].classHour;
							vm.coursename=vm.times[i].courseName;
							//;
							vm.compareTime(vm.times[i].startTime);
						}
					}
				}
				//全日制
				else
				{
					if(!val){this.showstudent=false;return;}
					let month=val.getMonth()+1;month=month<10?('0'+month):month;
					let dd=val.getDate();dd=dd<10?('0'+dd):dd;
					let selectDay=(val.getFullYear()+'-'+month+'-'+dd);
					vm.attend_daydayClassSyllabusId=[];
					for(let i =0;i<vm.times.length;i++){
						let daystr=vm.times[i].startTime.split(' ')[0];
						if(daystr==selectDay){
							// vm.classhour=vm.times[i].classHour;
							// vm.coursename=vm.times[i].courseName;
							vm.attend_daydayClassSyllabusId.push(vm.times[i].classSyllabusId);
							psyllabusId=vm.times[i].classSyllabusId;//全日制每日只有唯一一个classSyllabusId
							// vm.compareTime(vm.times[i].startTime);
							vm.editorAttendence = false;
						}
					}
				}
				//获取学生列表
				api.getAttendStudentList({syllabusId:psyllabusId}).then(function(data){
					 vm.studentlist = [];
					if(data.resultCode==2000){
						// debugger
						vm.studentlist=data.list.map(function(row){
							let parentName="";
							let phone = "";
							if(row.studentParentEntityList&&row.studentParentEntityList.length>0){
								parentName=row.studentParentEntityList[0].parentName;
								phone=row.studentParentEntityList[0].phone;
							}
							return {
									signinMode:1,
									realName:row.realName,
									courseName:row.courseName,
									parentName:parentName,
									phone:phone,
									studentId:row.studentId
							}
						});
						vm.showstudent=true;
					}
					else{
						vm.$message({
							type:'warning',
							message:data.message||'操作失败！'
						});
					}
					
				});
				
			},
			/**
			 * 与当前时间作比较
			 */
			compareTime(datetime){
				
				let currentTime = tool.DateToString(new Date(),"yyyy-MM-dd HH:mm");//当前系统时间
			
				if(currentTime>=datetime){
					this.editorAttendence = false;
				}else{
					this.editorAttendence = true;
				}
				
				
			},
			/**是否全日制班 */
			updateDayDayClassVisible(classId){
				
				let courseType=-1;
				for(let i=0;i<this.classlist.length;i++){
					if(this.classlist[i].classId==classId){
						
						courseType=this.classlist[i].classLevel;
						break;
					}
				}
				
				if(courseType==2){
					
					this.attend_daydayClass=true;
				}
				else{
					this.attend_daydayClass=false;
				}
				console.log(this.attend_daydayClass)
				console.log(this.tempattendWay)
			}

		},
		computed:{	
			
	    	...mapState({                            
						  isShow:state=>state.createAttendenceRecord.createAttendenceRecordDialog					
						}),
			...mapGetters("createAttendenceRecord",{
				classlist:"getClassList"
			}),           
            clslist:function(){
            	let clslist=[];           		           	
            	for(let i=0;i<this.classlist.length;i++){
					//停课一个月的课程排除掉 classStatusMode=3
					let row=this.classlist[i];
					let now=new Date();
					let tstr=row.updateTime.replace(/-/g,'/');
					let stopTime=new Date(tstr);
					if(row.classStatusMode==3&&tool.DaySpan(now,stopTime)>=30){
						// console.log(tstr)
						continue;
					}
					// if(this.classlist[i].classStatusMode==1||this.classlist[i].classStatusMode==2)
					{
            			clslist.push({
	            			classid:row.classId,
	            			className:row.className,
	            			courseName:row.courseName          			
            			})
            		}
            		
            	}            	
            	return clslist;
            }
       },
       mounted(){
       	    this.initData();
       	    vm=this;
       	    
	   }
		
	}
</script>

<style lang="scss">
	@import "@/style/module/utils.scss";
	.attendenceRecordContainer{
		
		.footer-btn{
			.btnOk{
				width:1.6rem;
				height: 0.4rem;
				font-size: 0.16rem;
				background: #3885F8;
				color: #FFFFFF;
				border-radius: .1rem;
			}
			.btnCancel{
				width:1.6rem;
				height: 0.4rem;
				font-size: 0.16rem;
				background: #FFFFFF;
				color: #333333;
				border-radius: .1rem;
			}
		}
		.recordlist{
			width:100%;			
			padding:0 .3rem 0 .3rem;
		
			.item{
				width:100%;
				height: .5rem;
				line-height: .5rem;				
			}
			.line{
				height: 1px;
				background: $partinglineColor;
				margin-bottom: .2rem;
				margin-top:.2rem;
			}
			.title{
				width: inherit;
				margin-bottom: .1rem;
				font-size: $titleFontSize;
				color: $importantwordColor;
			}
			.studentlist{
				width: 100%;				
				border:1px solid $bordercolor;
				border-radius: .1rem;
				padding:0 .1rem .1rem .1rem;
				.selectWay{
					width: inherit;
					height: .2rem;
					line-height: .2rem;
				}
				
				
			}
		}
		/**自定义对话框标题样式**/
		.panel_title{				
			padding:.23rem .31rem .23rem .31rem;
			font-size: .22rem;	
		    font-family: "microsoft yahei";
		    color: #333333;		
		}
		/**
		 * 自定义对话框样式
		 */
		.el-dialog-bg{
			background: #FFFFFF;
			width:10rem;
			border-radius: .1rem;
			.el-dialog__header{
				padding: 0px;
			}
			.el-dialog__body{
				padding: 0px !important;
			}	
			.el-dialog__footer{
				padding: .3rem;
				.footer-btn{
					width:100%;
					text-align: center;									
			   }
			}		
		}
	}
</style>